
#include <string>
#include <filesystem>
#include <iostream>

using namespace std;


int main(int argc, char* argv[])
{

    //first argument is the folder that contains the shader files to compile
    //second argument is the compiler path

    if (argc < 3)
    {
        printf("Not enough arguments\n");

        //print usage
        printf("Usage: ShaderCompiler <shader folder> <compiler path>\n");

        return 1;
    }

    std::string shaderFolder = argv[1];


    //find all files with extension .frag and .vert
    //compile them and output them in the same folder with the extension .spv
    std::filesystem::path path(shaderFolder);

    if (!std::filesystem::exists(path))
    {
        std::cerr<<"error:compile shader failed!" << "Path does not exist\n"<<shaderFolder <<std::endl;
        return 1;
    }

    std::string compilerPath = argv[2];
    std::filesystem::path compilerPathPath(compilerPath);
    if(!std::filesystem::exists(compilerPathPath))
    {
        std::cerr<<"error:compile shader failed!" << "Compiler path does not exist\n"<<compilerPath <<std::endl;
        return 1;
    }


    std::filesystem::directory_iterator end_itr;

    for (std::filesystem::directory_iterator itr(path); itr != end_itr; ++itr)
    {
        if (itr->path().extension() == ".frag" || itr->path().extension() == ".vert")
        {

            //check if the file already exist and the glsl file is not newer
            std::filesystem::path spvPath = itr->path();
            spvPath += ".spv";

            if (std::filesystem::exists(spvPath))
            {
                if (std::filesystem::last_write_time(itr->path()) < std::filesystem::last_write_time(spvPath))
                {
                    continue;
                }
            }

            std::string command = compilerPath + " -V " + itr->path().string() + " -o " + itr->path().string() + ".spv";

            //std::cout<<"execute:"<<command <<"\n"<<std::endl;

            system(command.c_str());
        }
    }


    return 0;

}